<!--
  -    Copyright (c) 2018-2025, gewu All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the gewucn.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: gewu
  -->
<template>
  <div class="execution">
    <el-card class="box-card btn-search page-search">
      <div slot="header" class="clearfix">
        <div class="btn-box">
          <el-button
            type="info"
            icon="el-icon-refresh-left"
            @click="refreshChange()"
          ></el-button>
          <el-button
            id="gwButton"
            type="primary"
            style="backgroundcolor: #e1b980"
            icon="el-icon-circle-plus-outline"
            v-if="permissions.ems_emsdistransfer_add"
            @click="cateAdd"
            >新增</el-button
          >
          <el-button
            type="success"
            icon="el-icon-edit"
            v-if="permissions.ems_emsdistransfer_edit"
            :disabled="single"
            @click="handleEdit"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-circle-close"
            v-if="permissions.ems_emsdistransfer_del"
            @click.native="handleDel()"
            :disabled="multiple"
            >删除</el-button
          >
          <el-button type="check" icon="el-icon-download" @click="exportExcel"
            >导出</el-button
          >
        </div>
        <div class="icon-box">
          <i class="el-icon-search" @click="searchShow"></i>
          <i class="el-icon-refresh" @click="refreshChange"></i>
          <i class="el-icon-goods"></i>
          <i class="el-icon-setting" @click="columnShow"></i>
          <i class="icon-zuixiaohua" />
        </div>
      </div>
    </el-card>
    <basic-container>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @selection-change="selectionChange"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @cell-click="cellClick"
        @row-del="handleDel"
        :before-open="handleOpenBefore"
        :cell-style="cellStyle"
      >
        <template slot="header">
          <IconTitle class="selfTitle" title="调拨转移" imgUrl="yunwei" />
        </template>


        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            v-if="permissions.ems_emsdistransfer_edit"
            @click="handleEdit(scope.row, scope.index)"
            >编辑</el-button
          >
          <el-button type="text" @click="relationDev(scope.row)">
            <i class="el-icon-view"></i>关联设备</el-button
          >
        </template>
      </avue-crud>
    </basic-container>
    <el-drawer
      class="drawerStyle"
      title="审批信息"
      :show-close="false"
      :visible.sync="detail"
      direction="rtl"
      size="45%"
      append-to-body
      :modal="false"
    >
      <div>
        <div>
          <span class="labelS">转移单号：</span>
          <span class="contentS">{{ detailInfo.transferNum }}</span>
        </div>
        <div>
          <span class="labelS">申请人：</span>
          <span class="contentS">{{ detailInfo.createBy }}</span>
        </div>
      </div>
      <div class="line"></div>
      <div>
        <el-card shadow="always" class="box-card">
          <IconTitle class="selfTitle" title="流程图" imgUrl="yunwei" />
          <img
            data-v-5f5e980e=""
            src="/act/process/resource/30101/LeaveBill:1:30104/image"
            width="100%"
          />
        </el-card>
      </div>
    </el-drawer>
    <SelectliableUser
      ref="selectLiable"
      v-if="selectLiableDia"
      :changeidentityDia.sync="selectLiableDia"
      @closeSelect="selectUser"
    ></SelectliableUser>
    <el-dialog
      :visible.sync="isRelate"
      width="80%"
      :show-close="false"
      class="relativeDev"
    >
      <DeviceRelate
        @cancel="cancel"
        v-if="isRelate"
        @comfire="comfireAdd"
        :listObj="readyDev"
      ></DeviceRelate>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
      
 <el-form-item label="审批结束时间" prop="applyEndTime" >
             <el-date-picker
              style="width: 100%"
      v-model="form.applyEndTime"
      type="date"
      format='yyyy-MM-dd hh:mm:ss'
      value-format='yyyy-MM-dd hh:mm:ss'
      placeholder="选择审批结束时间">
    </el-date-picker>
           
    </el-date-picker>
          </el-form-item>
        <el-form-item label="申请原因" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            :rows="2"
            placeholder="请输入申请原因"
          />
        </el-form-item>
          <el-form-item label="上传文件">
 <el-upload
            ref="upload"
            class="upload-demo"
            action="/admin/sys-file/upload"
            name="file"
            :headers="headers"
            :on-success="handleAvatarSuccess"
            :file-list="fileList"
            :auto-upload="true"
            :on-remove="handleFileRemove"
          >
            <el-button
              size="small"
              :disabled="fileList.length === 1"
              type="primary"
              >点击上传</el-button
            >
          </el-upload>
  </el-form-item>
   <el-form-item label="关联设备" v-if='readyDev.length>0' >
        <div class="tableStyle">
                <div v-for="item,index in readyDev" :key="item.id" >
                    <span :title='item.deviceName' class="colsx">{{item.deviceName}}</span>
                    <span :title='item.deviceNum' class="colsx">{{item.deviceNum}}</span>
                    <span class="action" @click="cancelDevice(item,index)">解除关联</span>
                </div>
              </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAdd">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import SelectliableUser from "@/views/ems/equipment/components/selectliableUser.vue";
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  addDev,
  getDevAnuth,
} from "@/api/ems/equipDisposal/allocation";

import DeviceRelate from "@/views/ems/inspection/components/deviceRelate";

import { tableOption } from "@/const/crud/ems/equipDisposal/allocation";
import { mapGetters } from "vuex";
import jQuery from "jquery";
import IconTitle from "@/components/icon-title/index.vue";
import store from "@/store";
import { delObjEquipDisposal } from "@/api/admin/sys-file";
import { color } from "echarts";

export default {
  name: "emsdistransfer",
  components: {
    IconTitle,
    SelectliableUser,
    DeviceRelate,
  },
  data() {
    return {
      tableData: [],
      searchForm: {}, // 查询参数
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      ids: [],
      selectionList: [],

      selectLiableDia: false,
      newName: "",
      newId: "",
      formName: {},

      headers: {
        Authorization: "Bearer " + store.getters.access_token,
      },
      fileList: [],

      detail: false,
      detailInfo: {},

      isRelate: false,
      devObject: {},
      readyDev: [],

      title: "新增",
      open: false,
      form: {
        id: null,
        applyEndTime: undefined,
        reason: null,
        fileIdArray: [],
      },
      rules: {
        applyEndTime: [
          { required: true, message: "请选择审批结束时间", trigger: "change" },
        ],
      },
      rowId: "",
    };
  },
  computed: {
    ...mapGetters(["permissions", "theme"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.ems_emsdistransfer_add, false),
        delBtn: this.vaildData(this.permissions.ems_emsdistransfer_del, false),
        editBtn: this.vaildData(
          this.permissions.ems_emsdistransfer_edit,
          false
        ),
      };
    },
  },
  mounted() {
    this.initElement();
    this.changeThme();
  },
  methods: {
    cateAdd() {
      this.title = "新增";
      this.open = true;
      this.reset();
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.form.id) {
            addObj(this.form).then((data) => {
              this.$message.success("添加成功");
              this.getList(this.page);
              this.open = false;
            });
          } else {
            putObj(this.form).then((data) => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList(this.page);
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 取消按钮
    cancelAdd() {
      this.open = false;
      this.reset();
    },
    //编辑
    async handleEdit(row) {
      this.open = true;
      this.title = "修改";
      let id = row ? row.id : this.selectionList[0].id;
      await this.getObjList(id);
      for (let key in this.form) {
        this.form[key] = this.detailInfo[key];
      }
      if (this.detailInfo.fileArray && this.detailInfo.fileArray.length > 0) {
        this.fileList = this.detailInfo.fileArray;
        this.fileList[0].name = this.detailInfo.fileArray[0].fileName;
      }
      if (row) {
        this.rowId = row.id;
        //关联设备
        getDevAnuth({ transferId: row.id }).then((res) => {
          this.readyDev = res.data.data;
        });
      }
    },
    reset() {
      this.form = {
        id: null,
        applyEndTime: undefined,
        reason: null,
        fileIdArray: [],
      };
      this.fileList = [];
      this.readyDev = [];
      this.rowId = "";
      this.resetForm("form");
    },
    cancel() {
      this.isRelate = false;
    },
    relationDev(row) {
      this.devObject = row;
      this.getDevAnuth(row.id);
    },
    cancelDevice(item, index) {
      let temObj = JSON.parse(JSON.stringify(this.readyDev));
      temObj.splice(index, 1);
      let ids = temObj.map((item) => {
        return item.deviceId;
      });
      addDev({ deviceIdList: ids, id: this.rowId }).then((res) => {
        if (res.data.code == 0) {
          this.readyDev.splice(index, 1);
          this.$message.success("解除成功");
        } else {
          this.$message.error("解除失败");
        }
      });
    },
    getDevAnuth(m) {
      getDevAnuth({ transferId: m }).then((res) => {
        this.readyDev = res.data.data;
        this.isRelate = true;
      });
    },
    comfireAdd(m) {
      addDev({ ...m, id: this.devObject.id }).then((res) => {
        if (res.data.code == 0) {
          this.$message.success("设备添加成功");
          this.isRelate = false;
        } else {
          this.$message.error("设备添加失败");
        }
      });
    },
    handleOpenBefore(show, type, row) {
      window.boxType = type;
      for (let key in this.form) {
        this.form[key] = undefined;
      }
      for (let key in this.formName) {
        this.formName[key] = undefined;
      }
      show();
    },
    selectUserDia(m, n) {
      this.selectLiableDia = true;
      this.newName = m;
      this.newId = n;
      this.$nextTick(() => {
        this.$refs.selectLiable.open();
      });
    },
    selectUser(row) {
      this.formName[this.newName] = row.username;
      this.form[this.newId] = row.userId;
      this.selectLiableDia = false;
    },
    cellStyle(data) {
      // 表格的第二列加上小手和padding为0
      if (data.columnIndex === 2) {
        return "color:#02b980;cursor:pointer";
      }
    },

    cellClick(row, column) {
      if (column.property === "transferNum") {
        this.$router.push({
          path: "/ems/equipDisposal/allocation/detail",
          query: { id: row.id },
        });
      } else {
        if (column.label != "操作") {
          this.detailInfo = row;
          this.detail = true;
        }
      }
    },
    initElement() {
      var mediumb = document.createElement("b"); //思路一样引入中间元素
      jQuery(".avue-crud__tip").after(mediumb);
      jQuery(".selfTitle").after(jQuery(".avue-crud__tip"));
      jQuery(mediumb).after(jQuery(".selfTitle"));
      jQuery(mediumb).remove();
    },
    selectionChange(list) {
      this.selectionList = list;
      this.single = list.length !== 1;
      this.multiple = !list.length;
      this.ids = list.map((item) => item.id);
    },

    columnShow() {
      this.$refs.crud.$refs.dialogColumn.columnBox = !0;
    },
    // 搜索框显示与否
    searchShow() {
      this.$refs.crud.$refs.headerSearch.searchShow =
        !this.$refs.crud.$refs.headerSearch.searchShow;
    },
    handleAvatarSuccess(response, file, fileList) {
      this.form.fileIdArray = [];
      this.fileList = fileList;
      this.form.fileIdArray.push(Number(this.fileList[0].response.data.fileId));
    },
    handleFileRemove(file, fileList) {
      delObjEquipDisposal(file.id).then((res) => {
        this.$message.success("删除成功");
        this.fileList = [];
        this.form.fileIdArray = [];
      });
    },
    // 列表查询
    getList(page, params) {
      this.tableLoading = true;
      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
          },
          params,
          this.searchForm
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    getObjList(id) {
      return new Promise((resolve, reject) => {
        getObj(id).then((res) => {
          this.detailInfo = res.data.data;
          resolve(); //异步处理
        });
      });
    },
    // 删除
    handleDel: function (row, index) {
      this.$confirm("是否确认删除所选数据项", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let id = "";
          if (row) {
            id = row.id;
          } else {
            id = this.ids;
          }
          return delObj(id);
        })
        .then((data) => {
          this.$message.success("删除成功");
          this.getList(this.page);
        });
    },
    // 每页条数改变事件
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    // 当前页发生改变事件
    currentChange(current) {
      this.page.currentPage = current;
    },
    // 查询事件
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    // 刷新事件
    refreshChange() {
      this.getList(this.page);
    },
    // 导出excel
    exportExcel() {
      this.downBlobFile(
        "/ems/emsdistransfer/export",
        this.searchForm,
        "emsdistransfer.xlsx"
      );
    },

    // 改变主题颜色
    changeThme() {
      //"#02b980"
      document.getElementById("gwButton").style.backgroundColor = this.theme;
    },
  },
};
</script>
<style scoped lang="scss">
.labelS {
  display: inline-block;
  width: 100px;
  margin-right: 10px;
  text-align: right;
  color: #888888;
  font-size: 12px;
}
.contentS {
  font-weight: bold;
  color: #101010;
  margin: 10px 0;
  display: inline-block;
  font-size: 14px;
}
.line {
  border: 2px solid rgba(236, 240, 244, 100);
  margin: 30px 0;
}
.tableStyle {
  div {
    display: flex;
    span {
      display: inline-block;
    }
    .colsx {
      width: 35%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .action {
      width: 30%;
      cursor: pointer;
      color: red;
    }
  }
}
::v-deep.drawerStyle {
  .el-drawer__header {
    background-color: #f2f2f5;
    padding: 20px 0 20px 20px;
    color: #101010;
    margin-bottom: 10px;
  }
  .el-card__body {
    padding: 0 20px 10px;
  }
  .box-card {
    box-shadow: 0px 0px 7px 0px #eff2f5;
    margin: 0 10px;
  }
  .tableTitle {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 20px;
    display: inline-block;
  }
}
::v-deep.relativeDev {
  .el-dialog__header {
    padding: 0;
  }
  .el-dialog__body {
    padding-top: 10px;
  }
}
</style>